package blingking.jfinal.orm.util;

import blingking.jfinal.orm.annotation.JFTable;
import blingking.jfinal.orm.bean.JFMappingBean;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.Set;

/**
 * @author King
 * @description
 * @Date 2020/3/22
 */
public class JFMappingBeanUtil {
    public static Set<JFMappingBean> scanMappingBeans(String[] packageNameArray, boolean isScanChild, String dataSourceName) throws ClassNotFoundException {
        Set<Class> classes = PackageScanUtil.scanModelClasses(packageNameArray, isScanChild);
        Set<JFMappingBean> jfMappingBeans = new HashSet<>();
        for (Class clazz : classes) {
            jfMappingBeans.add(generJFMappingBean(clazz,dataSourceName));
        }

        return jfMappingBeans;
    }
    private static JFMappingBean generJFMappingBean(Class clazz,String dataSourceName){
        JFTable jfTableAnnotation = AnnotationUtils.getAnnotation(clazz,JFTable.class);
        String tableName = clazz.getSimpleName();
        if(jfTableAnnotation!=null){
            if(!StringUtils.isEmpty(jfTableAnnotation.name())){
                tableName = jfTableAnnotation.name();
            }
            if (!StringUtils.isEmpty(jfTableAnnotation.dataSourceName())){
                dataSourceName = jfTableAnnotation.dataSourceName();
            }
        }
        JFMappingBean jfMappingBean = new JFMappingBean(tableName,clazz,dataSourceName);
        return jfMappingBean;
    }
}
